/*
 * @Author: lokei
 * @Date: 2022-10-27 00:12:30
 * @LastEditors: lokei
 * @LastEditTime: 2022-10-27 19:43:57
 * @Description: 
 */
package cn.lokei.task.entity.job;

import java.util.HashMap;
import java.util.Map;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSONObject;

import cn.lokei.task.entity.iot.mqtt.MyMqttClient;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LockPCJob extends QuartzJobBean {
    
    @SuppressWarnings("unchecked")
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("    Hi! :" + jobExecutionContext.getJobDetail().getKey());
        // String pid = jobExecutionContext.getJobDetail().getJobDataMap().getString("pid");
        // String gateway_identity = jobExecutionContext.getJobDetail().getJobDataMap().getString("gateway_identity");
        MyMqttClient mqttClient = (MyMqttClient) jobExecutionContext.getJobDetail().getJobDataMap().get("mqttClient");
        // MyMqttClient mqttClient = gatewayClientMap
        //         .get((!pid.equals("") ? pid + ":" : "") + gateway_identity + "_cloud");
        if (mqttClient != null) {
            JSONObject msg = new JSONObject();
            msg.put("msg", "1");
            mqttClient.publishMessage(jobExecutionContext.getJobDetail().getKey().getName(), msg.toJSONString(), 1);
            RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>) jobExecutionContext.getJobDetail().getJobDataMap().get("redisTemplate");
            Map<String, String> device_finish_map = new HashMap<String, String>();
            device_finish_map.put("pid", jobExecutionContext.getJobDetail().getJobDataMap().getString("pid"));
            device_finish_map.put("device_identity", jobExecutionContext.getJobDetail().getJobDataMap().getString("device_identity"));
            redisTemplate.opsForStream().add("device_finish", device_finish_map);
        }
        TriggerKey triggerKey = new TriggerKey(jobExecutionContext.getJobDetail().getKey().getName());
        try {
            jobExecutionContext.getScheduler().pauseTrigger(triggerKey);
            jobExecutionContext.getScheduler().unscheduleJob(triggerKey);
            jobExecutionContext.getScheduler().pauseJob(jobExecutionContext.getJobDetail().getKey());
            jobExecutionContext.getScheduler().deleteJob(jobExecutionContext.getJobDetail().getKey());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
